package com.dexgdx.game.manager;

import java.util.ArrayList;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.dexgdx.game.Game;
import com.dexgdx.game.constants.EMoveDirection;
import com.dexgdx.game.json.JSONAnimationObject;
import com.dexgdx.game.json.JSONManager;
import com.dexgdx.game.util.DexAnimation;

public class AnimationManager {

	public static void loadAnimationsFromJSON(){
		
		JSONManager.saveJSONAnimationObject();

		ArrayList<JSONAnimationObject> jSONAnimationObjects = JSONManager.getJSONAnimationObject();
		
		for (JSONAnimationObject jsonAnimationObject : jSONAnimationObjects) {
			
			Texture texture = new Texture(
					Gdx.files.internal("data/spritesheets/" + jsonAnimationObject.getSpriteSheetPath()));
	        TextureRegion[][] tmp = TextureRegion.split(texture, 
	        		texture.getWidth() / jsonAnimationObject.getColumnSize(), 
	        		texture.getHeight() / jsonAnimationObject.getRowSize());
	        
	        for (int rowIndex = 0; rowIndex < jsonAnimationObject.getRowSize(); rowIndex++) {
	        	EMoveDirection eMoveDirection = jsonAnimationObject.getMoveDirections().get(rowIndex);
	        	TextureRegion[] textureRegions = new TextureRegion[jsonAnimationObject.getColumnSize()];
	            int textureIndex = 0;
	            for (int colIndex = 0; colIndex < jsonAnimationObject.getColumnSize(); colIndex++) {
	            	if(!tmp[rowIndex][colIndex].isFlipY())
	            		tmp[rowIndex][colIndex].flip(false, true);
	            	textureRegions[textureIndex++] = tmp[rowIndex][colIndex];
	            }
	            AnimationInfoKey animationInfoKey = AnimationInfoKey.fromData(jsonAnimationObject, eMoveDirection.ordinal());
	            DexAnimation dexAnimation = new DexAnimation(eMoveDirection, jsonAnimationObject.getStopRowIndex(), 0.05f, textureRegions);
		        Game.animationData.animations.put(animationInfoKey.getKey(), dexAnimation);
	        }
		}
        Game.stateTime = 0f;  
	}

	public static DexAnimation getAnimationByKey(int playerNameId, int costumeNameId, int animationType){
		return getAnimationByKey(playerNameId, costumeNameId, animationType, 1);
	}
	
	public static DexAnimation getAnimationByKey(int playerNameId, int costumeNameId, int animationType, int moveDirection){
		AnimationInfoKey animationInfoKey = AnimationInfoKey.fromData(playerNameId, costumeNameId, animationType, moveDirection) ;
		return Game.animationData.getAnimations().get(animationInfoKey.getKey());
	}
}
